package com.yunsc.store.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunsc.common.exception.YunscException;
import com.yunsc.common.utils.PageResult;
import com.yunsc.store.dao.YunscDeliveryDao;
import com.yunsc.store.dto.StoreDeliveryDTO;
import com.yunsc.store.entity.YunscDeliveryEntity;
import com.yunsc.store.entity.YunscDeliveryRuleEntity;
import com.yunsc.store.service.YunscDeliveryRuleService;
import com.yunsc.store.service.YunscDeliveryService;
import com.yunsc.store.vo.StoreDeliveryVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;


@Service("yunscDeliveryService")
public class YunscDeliveryServiceImpl extends ServiceImpl<YunscDeliveryDao, YunscDeliveryEntity> implements YunscDeliveryService {


    @Resource
    private YunscDeliveryRuleService deliveryRulesService;


    @Override
    public List<YunscDeliveryEntity> queryDeliveryAll(Integer storeId) {
        LambdaQueryWrapper<YunscDeliveryEntity> lqw = new LambdaQueryWrapper<>();
        lqw.eq(YunscDeliveryEntity::getStoreId, storeId);
        lqw.eq(YunscDeliveryEntity::getIsDelete, 0);
        return this.list(lqw);
    }

    @Override
    public PageResult<YunscDeliveryEntity> queryDeliveryList(Integer page, String search, Integer storeId) {
        LambdaQueryWrapper<YunscDeliveryEntity> lqw = new LambdaQueryWrapper<>();
        lqw.eq(YunscDeliveryEntity::getStoreId, storeId);
        lqw.eq(YunscDeliveryEntity::getIsDelete, 0);
        lqw.like(StringUtils.isNotEmpty(search), YunscDeliveryEntity::getName, search);
        lqw.orderByDesc(YunscDeliveryEntity::getSort);
        List<YunscDeliveryEntity> deliveryList = this.list(lqw);
        return PageResult.formatPageResult(deliveryList, page, deliveryList.size(), deliveryList.size());
    }

    @Override
    @Transactional
    public void saveDelivery(StoreDeliveryDTO deliveryParams) {
        YunscDeliveryEntity delivery = new YunscDeliveryEntity();
        StoreDeliveryDTO.ExpressForm form = deliveryParams.getForm();
        BeanUtils.copyProperties(form, delivery);
        delivery.setStoreId(10001);
        boolean save = this.save(delivery);
        if (!save){
            throw new YunscException("保存失败");
        }
        List<StoreDeliveryDTO.RulesForm> rules = form.getRules();
        if (CollectionUtils.isEmpty(rules)){
            return;
        }
        List<YunscDeliveryRuleEntity> ruleEntityList = rules.stream().map(rule -> {
            YunscDeliveryRuleEntity deliveryRule = new YunscDeliveryRuleEntity();
            BeanUtils.copyProperties(rule, deliveryRule);
            deliveryRule.setFirst(rule.getFirst());
            deliveryRule.setFirstFee(rule.getFirstFee());
            deliveryRule.setDeliveryId(delivery.getDeliveryId());
            deliveryRule.setRegion(JSON.toJSONString(rule.getRegion()));
            deliveryRule.setRegionText(JSON.toJSONString(rule.getRegionText()));
            return deliveryRule;
        }).collect(Collectors.toList());
        deliveryRulesService.saveBatch(ruleEntityList);
    }

    @Override
    @Transactional
    public void updateDelivery(StoreDeliveryDTO deliveryParams) {
        Integer deliveryId = deliveryParams.getDeliveryId();
        YunscDeliveryEntity delivery = this.getById(deliveryId);
        if (delivery == null){
            throw new YunscException("该配送模板不存在");
        }

        BeanUtils.copyProperties(deliveryParams.getForm(), delivery);
        delivery.setDeliveryId(deliveryId);
        if (!this.updateById(delivery)) {
            throw new YunscException("修改失败");
        }
        LambdaQueryWrapper<YunscDeliveryRuleEntity> lqw = new LambdaQueryWrapper<>();
        lqw.eq(YunscDeliveryRuleEntity::getDeliveryId, deliveryId);
        boolean remove = deliveryRulesService.remove(lqw);
        if (!remove){
            throw new YunscException("修改失败");
        }
        List<StoreDeliveryDTO.RulesForm> rules = deliveryParams.getForm().getRules();
        if (CollectionUtils.isEmpty(rules)){
            return;
        }
        List<YunscDeliveryRuleEntity> ruleEntityList = rules.stream().map(rule -> {
            YunscDeliveryRuleEntity deliveryRule = new YunscDeliveryRuleEntity();
            BeanUtils.copyProperties(rule, deliveryRule);
            deliveryRule.setFirst(rule.getFirst());
            deliveryRule.setFirstFee(rule.getFirstFee());
            deliveryRule.setDeliveryId(deliveryId);
            deliveryRule.setRegion(JSON.toJSONString(rule.getRegion()));
            deliveryRule.setRegionText(JSON.toJSONString(rule.getRegionText()));
            return deliveryRule;
        }).collect(Collectors.toList());
        deliveryRulesService.saveBatch(ruleEntityList);
    }

    @Override
    @Transactional
    public void deleteDeliveryById(Integer deliveryId) {
        boolean update = this.update(new UpdateWrapper<YunscDeliveryEntity>().eq("delivery_id", deliveryId)
                .set("is_delete", 1));
        if (!update){
            throw new YunscException("删除失败");
        }
    }

    @Override
    public StoreDeliveryVO queryDeliveryDetail(Integer deliveryId) {
        YunscDeliveryEntity delivery = this.getById(deliveryId);
        if (delivery == null){
            throw new YunscException("配送模板不存在");
        }
        // 查询配送规则
        List<StoreDeliveryDTO.RulesForm> rules = deliveryRulesService.queryRuleList(deliveryId);

        StoreDeliveryVO deliveryVO = new StoreDeliveryVO();
        BeanUtils.copyProperties(delivery, deliveryVO);
        deliveryVO.setRule(rules);
        return deliveryVO;
    }

    @Override
    public YunscDeliveryRuleEntity queryDeliveryBigDecimalById(int deliveryId) {
        YunscDeliveryEntity delivery = this.getById(deliveryId);
        YunscDeliveryRuleEntity deliveryRule = deliveryRulesService.getOne(
                new QueryWrapper<YunscDeliveryRuleEntity>().eq("delivery_id", deliveryId));
        if (deliveryRule == null) {
            throw new YunscException("配送规则不存在");
        }
        deliveryRule.setMethod(delivery.getMethod());
        return deliveryRule;

    }

}